import { state } from "../config.js";
import { box, currentRole } from "../index.js";
import { allRolePosition } from "../role.js";
import { emit } from "../utils/scoket.js";
import { getRolePosition, setTransfrom } from "./newTransfrom.js";

//移动指令
let timer: any = {};
let lastKey = "";
export const move = (key: string) => {
  //速度频率
  if (typeof timer[key] === "number") return;
  timer[key] = setTimeout(
    () => (timer[key] = undefined),
    1000 / state.moveFrequency
  );
  const rolePosition = getRolePosition();

  switch (key) {
    case "a":
      if (rolePosition.x <= state.roleSpeed) {
        rolePosition.x = 0;
      } else {
        rolePosition.x -= state.roleSpeed;
      }
      currentRole.style.transform = setTransfrom(rolePosition);
      break;
    case "d":
      if (rolePosition.x >= box.boxW) {
        rolePosition.x = box.boxW;
      } else {
        rolePosition.x += state.roleSpeed;
      }
      currentRole.style.transform = setTransfrom(rolePosition);
      break;
    case "w":
      if (rolePosition.y - state.roleSpeed <= 0) {
        rolePosition.y = 0;
      } else {
        rolePosition.y -= state.roleSpeed;
      }
      currentRole.style.transform = setTransfrom(rolePosition);
      break;
    case "s":
      if (rolePosition.y + state.roleSpeed >= box.boxH) {
        rolePosition.y = box.boxH;
      } else {
        rolePosition.y += state.roleSpeed;
      }
      currentRole.style.transform = setTransfrom(rolePosition);
      break;
  }

  if (localStorage.role === "p1") {
    emit.p1("/key/down", {
      key,
      rolePosition: {
        w: allRolePosition.p1.w,
        h: allRolePosition.p1.h,
        ...rolePosition,
      },
    });
  } else if (localStorage.role === "p2") {
    emit.p2("/key/down", {
      key,
      rolePosition: {
        w: allRolePosition.p2.w,
        h: allRolePosition.p2.h,
        ...rolePosition,
      },
    });
  }
};
